package co.yixiang.modules.shop.service.impl;

import co.yixiang.modules.shop.domain.YxInvestOrder;
import co.yixiang.modules.shop.domain.YxInvestOrderCartInfo;
import co.yixiang.modules.shop.repository.YxInvestOrderCartInfoRepository;
import co.yixiang.modules.shop.repository.YxInvestOrderRepository;
import co.yixiang.modules.shop.repository.YxStoreProductLockRepository;
import co.yixiang.modules.shop.repository.YxStoreProductRepository;
import co.yixiang.modules.shop.service.SalesService;
import co.yixiang.modules.shop.service.YxInvestOrderService;
import co.yixiang.modules.shop.service.dto.SubscribeGoodsQueryCriteria;
import co.yixiang.modules.shop.service.dto.YxInvestOrderCartInfoDto;
import co.yixiang.modules.shop.service.dto.YxInvestOrderDto;
import co.yixiang.modules.shop.service.dto.YxInvestOrderQueryCriteria;
import co.yixiang.modules.shop.service.mapper.YxInvestOrderMapper;
import co.yixiang.utils.QueryHelp;
import co.yixiang.utils.ValidationUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author frq
 * @date 2020-06-10
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxInvestOrderServiceImpl implements YxInvestOrderService {
    @Autowired
    private YxInvestOrderRepository yxInvestOrderRepository;
    @Autowired
    private YxInvestOrderMapper yxInvestOrderMapper;

    @Autowired
    private YxInvestOrderCartInfoRepository yxInvestOrderCartInfoRepository;

    @Autowired
    private SalesService salesService;

    @Autowired
    private YxStoreProductLockRepository yxStoreProductLockRepository;

    @Autowired
    private YxStoreProductRepository yxStoreProductRepository;


    @Override
    public Map<String, Object> queryAll(YxInvestOrderQueryCriteria criteria, Pageable pageable) {
        Page<YxInvestOrder> page = yxInvestOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<YxInvestOrderDto> orderDtos = new ArrayList<>();
        for (YxInvestOrder investOrder : page.getContent()) {
            YxInvestOrderDto orderDto = yxInvestOrderMapper.toDto(investOrder);
            //根据订单ID获取购物车详情信息
            List<YxInvestOrderCartInfo> cartInfos = yxInvestOrderCartInfoRepository.findByOrderId(String.valueOf(orderDto.getId()));
            List<YxInvestOrderCartInfoDto> cartInfosDtos = new ArrayList<>();
            for (YxInvestOrderCartInfo cartInfo : cartInfos) {
                YxInvestOrderCartInfoDto cartInfoDto = new YxInvestOrderCartInfoDto();
                cartInfoDto.setCartInfoMap(JSON.parseObject(cartInfo.getCartInfo()));
                cartInfosDtos.add(cartInfoDto);
            }
            orderDto.setCartInfoList(cartInfosDtos);
            orderDto.setSalesDTO(salesService.findById(orderDto.getSalesManId()));
            orderDtos.add(orderDto);
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", orderDtos);
        map.put("totalElements", page.getTotalElements());
        return map;
    }

    @Override
    public List<YxInvestOrderDto> queryAll(YxInvestOrderQueryCriteria criteria) {
        return yxInvestOrderMapper.toDto(yxInvestOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public YxInvestOrderDto findById(Integer id) {
        YxInvestOrder yxInvestOrder = yxInvestOrderRepository.findById(id).orElseGet(YxInvestOrder::new);
        ValidationUtil.isNull(yxInvestOrder.getId(), "YxInvestOrder", "id", id);
        return yxInvestOrderMapper.toDto(yxInvestOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YxInvestOrderDto create(YxInvestOrder resources) {
        return yxInvestOrderMapper.toDto(yxInvestOrderRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(YxInvestOrder resources) {
        YxInvestOrder yxInvestOrder = yxInvestOrderRepository.findById(resources.getId()).orElseGet(YxInvestOrder::new);
        ValidationUtil.isNull(yxInvestOrder.getId(), "YxInvestOrder", "id", resources.getId());
        yxInvestOrder.copy(resources);
        yxInvestOrderRepository.save(yxInvestOrder);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            yxInvestOrderRepository.deleteById(id);
        }
    }

    /**
     * 统计业务员提成
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findSalesCommission() {
        return yxInvestOrderRepository.findSalesCommission();
    }

    /**
     * 获取投资到期订单ID
     *
     * @return
     */
    @Override
    public List<Integer> findByListOrderId() {
        return yxInvestOrderRepository.findByListOrderId();
    }

    /**
     * 修改订单认购状态
     *
     * @param id
     * @param investStatus
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInvestStatus(Integer id, int investStatus) {
        yxInvestOrderRepository.updateInvestStatus(id, investStatus);
    }

    /**
     * 查询已认购的商品
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> findListSubscribeGoods(SubscribeGoodsQueryCriteria criteria, Pageable pageable) {
        Page<Map> page = yxInvestOrderRepository.findListSubscribeGoods(criteria.getStoreName(), criteria.getBeginDate(), criteria.getEndDate(),
                                                        criteria.getInvestName(), criteria.getInvestPhone(), pageable);
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getContent());
        map.put("totalElements", page.getTotalElements());
        return map;
    }
    /**
     * 查询商品ID
     * @param orderId 投资订单ID
     * @return
     */
    @Override
    public List<Integer> findListProductId(Integer orderId){
        return yxInvestOrderRepository.findListProductId(orderId);
    }
    /**
     * 更新商品为已投资商品
     * @param productId
     * @param isInvested
     * @param investName
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateIsInvested(Integer productId, int isInvested,String investName){
        yxInvestOrderRepository.updateIsInvested(productId,isInvested,investName);
    }
    /**
     * 查询支付超时的商品ID
     * @param investStatus
     * @param payTimeout
     * @return
     */
    @Override
    public List<Map<String,Integer>> findListGoods(int investStatus, String payTimeout){
           return yxInvestOrderRepository.findListGoods(investStatus,payTimeout);
    }

    /**
     * 更新支付超时的订单
     * @param map
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentTimeout(Map<String,Integer> map){
        yxInvestOrderRepository.updateInvestStatus(map.get("id"),5);
        yxStoreProductLockRepository.updateReleaser(String.valueOf(map.get("productId")),"系统");
        yxStoreProductRepository.updateLockStatus(String.valueOf(map.get("productId")),0);
    }
    /**
     * 更新订单支付状态
     * @param id
     * @param paid
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePayStatus(Integer id, Integer paid) {
        yxInvestOrderRepository.updatePayStatus(id,paid);
    }

    @Override
    public List<Map<String, Object>> getMachine(int number) {
        return yxInvestOrderRepository.getMachine(number);
    }
}